<?php
class MDealPaymentModel extends MDeal
{
	public function relations()
	{
		return CMap::mergeArray(parent::relations(),array(
			'orders' => array(self::MANY_MANY, 'MPaymentOrder', '{{PaymentOrderItem}}(itemId,orderId)',
				'joinType' => 'INNER JOIN',
				'on' => "orders_orders.`itemModule` = 'deal' AND orders.`status` = 2",
			),
		));
	}
	
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}
	
	public function getFunds()
	{
		static $f = array();
		if(!isset($f[$this->id]))
		{
			if(!count($this->orders))
				$f[$this->id] = 0;
			else
			{
				$ids = array();
				foreach($this->orders as $o)
					$ids[] = $o->id;
				$query = "SELECT SUM(quantity) AS total FROM {{PaymentOrderItem}} WHERE orderId IN (".implode(',',$ids).")
					AND itemModule = 'deal' AND itemId = ".$this->id;
				$f[$this->id] = app()->db->createCommand($query)->queryScalar();
			}
		}
		return $f[$this->id];
	}
	
	public function getCommissionHeld()
	{
		$commission = $this->getModule()->param('commission');
		if($this->company->commission)
			$commission = $this->company->commission;
		if($this->commission)
			$commission = $this->commission;
		return round(($this->funds * $this->price)/100*$commission,2);
	}
	
	public function search()
	{
		$criteria=new CDbCriteria;
		
		$criteria->with = array('stats');
		
		$criteria->compare('t.active',1);
		
		if($this->status)
			$criteria->compare('t.status',$this->status);
		else
			$criteria->compare('t.status','<>2');
			
		$criteria->compare('t.id',$this->id);
		
		$criteria->mergeWith(new CDbCriteria(array(		
			'condition' => '(t.purchaseMax is not null
				AND t.purchaseMax > 0 AND stats.bought >= t.purchaseMax) OR t.end <= :time',
			'params' => array(':time' => time()),
		)));
		
		return new CActiveDataProvider(__CLASS__, array('criteria'=>$criteria));
	}
}